package com.miniapp.core.utils;

import com.miniapp.common.enums.PaicFtiPolicyStatus;
import com.miniapp.common.gen.domain.PaicFtiPolicy;
import com.miniapp.common.gen.mapper.PaicFtiPolicyMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 平安货运险提交投保
 */
@Component
public class PaicFtiSubmitInsuranceApplicationUtils {

    private Logger logger = LoggerFactory.getLogger(PaicFtiSubmitInsuranceApplicationUtils.class);

    @Autowired
    private PaicFtiPolicyMapper paicFtiPolicyMapper;

    /**
     * 点击提交
     * @param chromeDriver
     */
    public void clickSubmit(ChromeDriver chromeDriver){
        //1、获取提交按钮
        logger.info("开始点击提交按钮");
        WebElement submitXPath = chromeDriver.findElementByXPath("//*[@id=\"mainSection\"]/div/section/div[3]/button[2]");
        submitXPath.click();
        logger.info("提交按钮点击完成");

        //处理弹框
        this.handleConfirm(chromeDriver);















    }

    /**
     * 点击提交后处理弹窗
     */
    public void handleConfirm(ChromeDriver chromeDriver){
        logger.info("开始处理弹窗");

        for (int i = 0; i < 50; i++) {
            ThreadUtils.threadSleep(200);
            List<WebElement> elementList = chromeDriver.findElementsByClassName("ivu-modal-confirm-head-title");
            logger.info("获取到弹窗："+elementList.size());
            if(CollectionUtils.isNotEmpty(elementList) && elementList.size() == 2){
                logger.info("跳出循环,获取到弹窗个数为："+elementList.size());
                break;
            }

            if(succeedInsuredResult(chromeDriver)){
                //投保成功
                return;
            }
            logger.info("继续循环");
        }


        List<WebElement> confirmHeadTitleList = chromeDriver.findElementsByClassName("ivu-modal-confirm-head-title");
        logger.info("=======================》获取到弹窗个数为："+confirmHeadTitleList.size());
        //confirmHeadTitleList.size() == 2说明有弹窗
        if(CollectionUtils.isNotEmpty(confirmHeadTitleList) && confirmHeadTitleList.size() == 2){
            //confirmHeadTitleList.size() == 2说明有提示框
            WebElement confirmHeadTitleElement = confirmHeadTitleList.get(confirmHeadTitleList.size() - 1);
            String titleElementText = confirmHeadTitleElement.getText();
            logger.info("弹出框抬头："+titleElementText);
            //提示内容
            List<WebElement> elementsByClassNameList = chromeDriver.findElementsByClassName("ivu-modal-confirm-body");
             WebElement confirmBodyElement = elementsByClassNameList.get(elementsByClassNameList.size() - 1);
            String bodyElementText = confirmBodyElement.getText();
            logger.info("弹出框内容提供："+bodyElementText);
            //弹出框按钮
            List<WebElement> confirmFooterElementList = chromeDriver.findElementsByClassName("ivu-modal-confirm-footer");
            WebElement confirmFooterElement = confirmFooterElementList.get(confirmFooterElementList.size() - 1);
            List<WebElement> buttonList = confirmFooterElement.findElements(By.tagName("button"));
             for (WebElement webElement : buttonList) {
                String text = webElement.getText();
                logger.info("按钮："+text);
            }

             if("温馨提示".equals(titleElementText)){
                //清除页面上的其他提示，信息填写不完整弹窗直接抛异常
                if("请按页面提示输入信息".equals(bodyElementText)){
                    logger.info("点击提交保单按钮页面提示信息未填写完整");
                    this.deficiencyResult(bodyElementText);
                    throw new RuntimeException("请按页面提示输入信息");
                }else if(CollectionUtils.isNotEmpty(buttonList) && buttonList.size() == 1){
                    buttonList.get(0).click();
                    //在此点击提交
                    clickSubmit(chromeDriver);
                }
            }else if("自然灾害提醒".equals(titleElementText)){
                //点击继续投保
                 for (WebElement buttnElement : buttonList) {
                     String text = buttnElement.getText();
                      if("继续投保".equals(text)){
                        buttnElement.click();
                        //点击完“继续投保”后继续处理弹窗
                          insuredResult(chromeDriver);
                        break;
                    }
                }
            }else if("投保失败".equals(titleElementText)){
                 insuredResult(chromeDriver);
             }


        }
    }

    /**
     * 处理投保结果
     * @param chromeDriver
     */
    public void insuredResult(ChromeDriver chromeDriver){

        for (int i = 0; i < 100; i++) {
            ThreadUtils.threadSleep(200);
            List<WebElement> confirmHeadTitleList = chromeDriver.findElementsByClassName("ivu-modal-confirm-head-title");
            ////confirmHeadTitleList.size() == 2说明有弹窗
            if(CollectionUtils.isNotEmpty(confirmHeadTitleList) && confirmHeadTitleList.size() == 2){
                try {
                    WebElement confirmHeadTitleElement = confirmHeadTitleList.get(confirmHeadTitleList.size() - 1);
                    String headTitleElementText = confirmHeadTitleElement.getText();
                    logger.info("等待投保结果====》弹出框抬头："+headTitleElementText);
                    //提示内容
                    List<WebElement> elementsByClassNameList = chromeDriver.findElementsByClassName("ivu-modal-confirm-body");
                    WebElement confirmBodyElement = elementsByClassNameList.get(elementsByClassNameList.size() - 1);
                    String bodyElementText = confirmBodyElement.getText();
                    logger.info("等待投保结果====》弹出框内容提供："+bodyElementText);
                    //弹出框按钮
                    List<WebElement> confirmFooterElementList = chromeDriver.findElementsByClassName("ivu-modal-confirm-footer");
                    WebElement confirmFooterElement = confirmFooterElementList.get(confirmFooterElementList.size() - 1);
                    List<WebElement> buttonList = confirmFooterElement.findElements(By.tagName("button"));
                    for (WebElement webElement : buttonList) {
                        String text = webElement.getText();
                        logger.info("等待投保结果====》按钮："+text);
                    }
                    if("投保失败".equals(headTitleElementText)){
                        logger.info("等待投保结果====》获取到投保失败");
                        logger.info("投保失败：开始更新保单信息");
                        PaicFtiPolicy paicFtiPolicy = PaicFtiUtils.localPaicFtiPolicy.get();
                        paicFtiPolicy.setPolicyStatus(PaicFtiPolicyStatus.FAILURE_TO_INSURE.getCode());
                        paicFtiPolicy.setPolicyMessage(bodyElementText);
                        paicFtiPolicyMapper.updateByPrimaryKeySelective(paicFtiPolicy);
                        logger.info("投保失败更新保单信息完成");
                        return;
                    }
                }catch (Exception e){
                    logger.info("等待投保结果====》点击继续投保后,获取‘投保成功’或‘投保失败’ 弹框失败，继续等待200毫秒，总共等待："+(200 * (i+1)+"毫秒"));
                }
            }

            if(succeedInsuredResult(chromeDriver)){
                return;

            }


        }


    }

    /**
     * 处理投保成功结果
     * @param chromeDriver
     * @return
     */
    public boolean succeedInsuredResult(ChromeDriver chromeDriver){
//        投保成功，生成保单号
        List<WebElement> pElementList = chromeDriver.findElementsByTagName("p");
        for (WebElement pWebElement : pElementList) {
            String pWebElementText = pWebElement.getText();
            if(StringUtils.isNotBlank(pWebElementText) && pWebElementText.contains("投保成功，生成保单号")){
                logger.info("投保成功更新保单");
                String policyNo = pWebElementText.substring(10, 30);
                logger.info("投保成功保单号为："+policyNo);
                PaicFtiPolicy paicFtiPolicy = PaicFtiUtils.localPaicFtiPolicy.get();
                paicFtiPolicy.setPolicyStatus(PaicFtiPolicyStatus.SUCCESSFUL_INSURANCE.getCode());
                paicFtiPolicy.setPolicyNo(policyNo);
                paicFtiPolicy.setPolicyMessage(pWebElementText);
                paicFtiPolicyMapper.updateByPrimaryKeySelective(paicFtiPolicy);
                return true;
            }
        }
        return false;
    }

    /**
     * 弹窗提示：请按页面提示输入信息，处理投保结果
     * @param policyMessage
     */
    public void deficiencyResult(String policyMessage){
        PaicFtiPolicy paicFtiPolicy = PaicFtiUtils.localPaicFtiPolicy.get();
        paicFtiPolicy.setPolicyStatus(PaicFtiPolicyStatus.FAILURE_TO_INSURE.getCode());
        paicFtiPolicy.setPolicyMessage(policyMessage);
        paicFtiPolicyMapper.updateByPrimaryKeySelective(paicFtiPolicy);
    }














}
